package com.rundatop.wx.controller;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpRequest;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.druid.support.logging.Log;
import com.alibaba.druid.support.logging.LogFactory;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.common.utils.HttpUtil;
import com.apistd.uni.Uni;
import com.apistd.uni.UniException;
import com.apistd.uni.UniResponse;
import com.apistd.uni.sms.UniMessage;
import com.apistd.uni.sms.UniSMS;
import com.rundatop.core.util.DateTimeUtil;
import com.rundatop.core.util.MD5Util;
import com.rundatop.core.util.ResponseUtil;
import com.rundatop.dao.model.BaseBrand;
import com.rundatop.dao.model.BasePhone;
import com.rundatop.dao.model.BaseVideo;
import com.rundatop.dao.model.Provinces;
import com.rundatop.dao.model.User;
import com.rundatop.wx.annotation.LoginUser;
import com.rundatop.wx.service.BaseBrandService;
import com.rundatop.wx.service.BaseGoodsService;
import com.rundatop.wx.service.BasePhoneService;
import com.rundatop.wx.service.BaseVideoService;
import com.rundatop.wx.service.ProvincesService;
import com.rundatop.wx.service.SmsService;
import com.rundatop.wx.service.StoreService;
import com.rundatop.wx.service.UserService;
import com.rundatop.wx.util.HttpRequestUtil;
import com.rundatop.wx.util.WxUtil;
import com.sun.net.ssl.internal.www.protocol.https.HttpsURLConnectionOldImpl;

@RestController
@RequestMapping("/wx/api")
public class WxAppController  extends BaseController{
	private final Log logger = LogFactory.getLog(WxAppController.class);

    @Autowired
    private UserService userService;
    @Resource
    private BaseBrandService baseBrandService;
    @Resource
    private BasePhoneService basePhoneService;
    @Resource
    private BaseGoodsService goodsService;
    @Resource
    private ProvincesService provincesService;
    @Resource
    private StoreService storeService;
    @Resource
    private BaseVideoService baseVideoService;
    @Resource
    private SmsService smsService;
    
    @GetMapping(value = {"getLists"})
    public Object getLists(BaseBrand condition) {
    	Object a = JSONArray.toJSON(baseBrandService.getList(condition));
    	return a;
    }
    
    @GetMapping(value = {"getVideo"})
    public Object getVideo(BaseVideo condition) {
    	Object a = JSONArray.toJSON(baseVideoService.getVideo(condition));
    	return a;
    }
    
    @GetMapping(value = {"getProvincesAndCities"})
    public Object getProvincesAndCities() {
    	Object a = JSONArray.toJSON(provincesService.getProvincesAndCities());
    	return a;
    }
    
    @GetMapping(value = {"getStore"})
    public Object getStore(String id, String loc) {
    	Object a = JSONArray.toJSON(storeService.getStroe(id, loc));
    	return a;
    }
    
    @GetMapping(value = {"getCity"})
    public Object getCity(String loc) {
    	Object a = JSONArray.toJSON(storeService.getPoi(loc));
    	return a;
    }
    
    @GetMapping(value = {"getPhoneAndGoods"})
    public Object getPhoneAndGoods(String id) {
    	Object a = JSONArray.toJSON(basePhoneService.getPhoneAndGoods(id));
    	return a;
    }
    
    @GetMapping(value = {"getPhones"})
    public Object getPhones(String id) {
    	Object a = JSONArray.toJSON(basePhoneService.selectByBrandId(id));
    	return a;
    }
    
    @GetMapping(value = {"getGoods"})
    public Object getGoods(String id, String text) {
    	Object aa = goodsService.getGoods(id, text);
    	Object a = JSONArray.toJSON(aa);
        System.out.println(a);
    	return a;
    }
    
    @GetMapping("getSetMeal")
    public Object getSetMeal(@LoginUser String userId) {
//    	String echoStr = getEchoStr();
//    	String echoStrPass = getEchoStrPass(echoStr);
//    	String data=HttpRequestUtil.sendGet("http://121.40.114.120:9000/", "Account=lxsj&DBTYPE=RY_HUIYUAN&OPENID="+userId+"&Method=PRO_WeiXin_GetJCLast&EchoStr="+echoStr+"&EchoStrPass="+echoStrPass);
//    	System.out.println(userId);
    	User user = userService.getById("ojGtA6DbcroOf6zsTG4SoSkVVHMQ");
    	if (user!=null) {
    		String data=HttpRequestUtil.sendGet("http://121.37.105.152:8080/pack/packRecord/getMemberPackRecordListWX", "phone="+user.getPhone());
        	System.out.println(data);
        	return data;
		} else {
			return "";
		}
    }
    
    @GetMapping("getRecord")
    public Object getRecord(@LoginUser String userId) {
//    	String echoStr = getEchoStr();
//    	String echoStrPass = getEchoStrPass(echoStr);
//    	String data=HttpRequestUtil.sendGet("http://121.40.114.120:9000/", "Account=lxsj&DBTYPE=RY_HUIYUAN&OPENID="+userId+"&Method=PRO_WeiXin_GetJCCost&EchoStr="+echoStr+"&EchoStrPass="+echoStrPass);
//    	System.out.println(userId);
    	User user = userService.getById(userId);
    	if (user!=null) {
    		String data=HttpRequestUtil.sendGet("http://121.37.105.152:8080/consume/packConsume/getMemberConsumeListWX", "phone="+user.getPhone());
    		return data;
    	} else {
    		return "";
    	}
    }
    
//    public static void main(String[] args) {
////    	String echoStr = getEchoStr();
////    	String echoStrPass = getEchoStrPass(echoStr);
////    	String data=HttpRequestUtil.sendGet("http://121.40.114.120:9000/", "Account=lxsj&DBTYPE=RY_HUIYUAN&OPENID=ojGtA6OXTtGqsUsaxEYutSi_6EvI&Method=PRO_WeiXin_GetJCCost&EchoStr="+echoStr+"&EchoStrPass="+echoStrPass);
//    	String data=HttpRequestUtil.sendPost("https://uni.apistd.com/?action=sms.message.send&accessKeyId=YOUR_ACCESS_KEY_ID/", "to=15165611976&signature=合一短信&templateId=pub_verif_identity");
//		System.out.println(data);
//    }
//    @GetMapping("verifyCode")
//    public Object verifyCode(@LoginUser String userId, String phone, String code) {
//    	String msg = "";
//    	String echoStr = getEchoStr();
//    	String echoStrPass = getEchoStrPass(echoStr);
//    	String data=HttpRequestUtil.sendGet("http://121.40.114.120:9000/", "Account=lxsj&DBTYPE=RY_HUIYUAN&OPENID="+userId+"&Method=PRO_WeiXin_ClientBind&EchoStr="+echoStr+"&EchoStrPass="+echoStrPass+"&Mobile="+phone+"&INDENTFYCODE="+code);
//    	Map<String, Object> bindResult = HttpRequestUtil.getData(data);
//    	if (bindResult!=null) {
//    		String ReturnCode =  bindResult.get("ReturnCode")+"";
//			if (ReturnCode!=null && ReturnCode.equals("0")) {
//				//绑定成功后,获取用户信息,更新注册时间/注册门店
//				
//				String userInfo=HttpRequestUtil.sendGet("http://121.40.114.120:9000/", "Account=lxsj&DBTYPE=RY_HUIYUAN&OPENID="+userId+"&Method=PRO_WeiXin_GetClientInfo&EchoStr="+echoStr+"&EchoStrPass="+echoStrPass);
//				Map<String, Object> userInfoResult = HttpRequestUtil.getData(userInfo);
//				User user = userService.getById(userId);
//				if (user!=null) {
//					if (userInfoResult != null) {
//						String shop = userInfoResult.get("T_L_SHOP_NAME")+"";
//						user.setF1(shop);
//					}
//					user.setPhone(phone);
//					userService.updateByPrimaryKeySelective(user);
//					return ResponseUtil.ok();
//				}
//	    	 } else {
//	    		 msg = bindResult.get("ReturnMsg")+"";
//	    		 return ResponseUtil.fail(Integer.valueOf(ReturnCode), msg);
//			}
//		}
//    	return null;
//    }
    
    @GetMapping("changeMobile")
    public Object changeMobile(@LoginUser String userId, String phone, String code) {
    	String msg = "";
    	String echoStr = getEchoStr();
    	String echoStrPass = getEchoStrPass(echoStr);
    	String data=HttpRequestUtil.sendGet("http://121.40.114.120:9000/", "Account=lxsj&DBTYPE=RY_HUIYUAN&OPENID="+userId+"&Method=PRO_WeiXin_ClientBind&EchoStr="+echoStr+"&EchoStrPass="+echoStrPass+"&Mobile="+phone+"&INDENTFYCODE="+code);
    	Map<String, Object> bindResult = HttpRequestUtil.getData(data);
    	if (bindResult!=null) {
    		String ReturnCode =  bindResult.get("ReturnCode")+"";
			if (ReturnCode!=null && ReturnCode.equals("0")) {
				//绑定成功后,获取用户信息,更新注册时间/注册门店
				
				String userInfo=HttpRequestUtil.sendGet("http://121.40.114.120:9000/", "Account=lxsj&DBTYPE=RY_HUIYUAN&OPENID="+userId+"&Method=PRO_WeiXin_ChangeMobile&EchoStr="+echoStr+"&EchoStrPass="+echoStrPass);
				Map<String, Object> userInfoResult = HttpRequestUtil.getData(userInfo);
				User user = userService.getById(userId);
				if (user!=null) {
					if (userInfoResult != null) {
						String shop = userInfoResult.get("T_L_SHOP_NAME")+"";
						user.setF1(shop);
					}
					user.setPhone(phone);
					userService.updateByPrimaryKeySelective(user);
					return ResponseUtil.ok();
				}
	    	 } else {
	    		 msg = bindResult.get("ReturnMsg")+"";
	    		 return ResponseUtil.fail(Integer.valueOf(ReturnCode), msg);
			}
		}
    	return null;
		
    }
    
    @GetMapping("getUserInfo")
    public Object getUserInfo(@LoginUser String userId) {
    	if (userId != null) {
    		User user = userService.getById(userId);
    		return user;
		}
		return null;
    }
    
//    @GetMapping("SendSms")
//    public Object SendSms(@LoginUser String userId, String phone) {
//    	String echoStr = getEchoStr();
//    	String echoStrPass = getEchoStrPass(echoStr);
//    	String data=HttpRequestUtil.sendGet("http://121.40.114.120:9000/", "Account=lxsj&DBTYPE=RY_HUIYUAN&OPENID="+userId+"&Method=SendSms&EchoStr="+echoStr+"&EchoStrPass="+echoStrPass+"&Mobile="+phone);
////    	System.out.println(userId);
//		return data;
//    }
    
    @GetMapping("SendSms")
    public Object SendSms(@LoginUser String userId, String phone) {
    	int code = smsService.getSms(phone);
		return code;
    }
    
    @GetMapping("verifyCode")
    public Object verifyCode(String phone, int code) {
    	String msg = "";
    	if (StringUtils.isNoneEmpty(phone)) {
    		String message = smsService.verifyCode(phone, code);
    		if (message!= null && message.equals("200")) {
    			User user = userService.getById("ojGtA6DbcroOf6zsTG4SoSkVVHMQ");
    			if (user!=null) {
					user.setPhone(phone);
					userService.updateByPrimaryKeySelective(user);
					return ResponseUtil.ok();
				}
			} else {
	    		 return ResponseUtil.fail(500, "验证码错误");
			}
		} else {
   		 return ResponseUtil.fail(500, "参数错误");
		}
//		if (ReturnCode!=null && ReturnCode.equals("0")) {
//		//绑定成功后,获取用户信息,更新注册时间/注册门店
//		
//		String userInfo=HttpRequestUtil.sendGet("http://121.40.114.120:9000/", "Account=lxsj&DBTYPE=RY_HUIYUAN&OPENID="+userId+"&Method=PRO_WeiXin_GetClientInfo&EchoStr="+echoStr+"&EchoStrPass="+echoStrPass);
//		Map<String, Object> userInfoResult = HttpRequestUtil.getData(userInfo);
//		User user = userService.getById(userId);
//		if (user!=null) {
//			if (userInfoResult != null) {
//				String shop = userInfoResult.get("T_L_SHOP_NAME")+"";
//				user.setF1(shop);
//			}
//			user.setPhone(phone);
//			userService.updateByPrimaryKeySelective(user);
//			return ResponseUtil.ok();
//		}
//	 } else {
//		 msg = bindResult.get("ReturnMsg")+"";
//		 return ResponseUtil.fail(Integer.valueOf(ReturnCode), msg);
//	}
    	return null;
    }
    
    @GetMapping("checkBind")
    public Object checkBind(@LoginUser String userId) {
    	String echoStr = getEchoStr();
    	String echoStrPass = getEchoStrPass(echoStr);
    	String data=HttpRequestUtil.sendGet("http://121.40.114.120:9000/", "Account=lxsj&DBTYPE=RY_HUIYUAN&OPENID="+userId+"&Method=PRO_WeiXin_ClientAlreadyBind&EchoStr="+echoStr+"&EchoStrPass="+echoStrPass);
//    	System.out.println(userId);
		return data;
    }
	 private static String getEchoStrPass(String echoStr) {
		 MD5Util md5 = new MD5Util();
		// TODO Auto-generated method stub
		 String echoStrPass = md5.MD5Encode("ran"+echoStr+"yue");
		 return echoStrPass;
	}
	 private static String getEchoStr() {
		 SimpleDateFormat format = new SimpleDateFormat("YYYYMMDDHHMMSS");
		 String date = format.format(new Date());
		 return date;
	}
	 
	 public static String ACCESS_KEY_ID = "PdeKWD8LSzEEYVcdFLQ2qz2Fwz9JpYs2ixwU4BWDFdqsAEh9W";
	    private static String ACCESS_KEY_SECRET = "your access key secret";

	    public static void main(String[] args) {
	    	
//	    	String date = DateTimeUtil.getPreTime(DateTimeUtil.dateFormat(new Date()), "-30");
//			System.out.println(date);
//			
//	    	System.out.println();
	        // 初始化
	        Uni.init(ACCESS_KEY_ID, ACCESS_KEY_SECRET); // 若使用简易验签模式仅传入第一个参数即可

	        // 设置自定义参数 (变量短信)
	        Map<String, String> templateData = new HashMap<String, String>();
	        templateData.put("code", "6666");
	        templateData.put("ttl", "30");

	        // 构建信息
	        UniMessage message = UniSMS.buildMessage()
	            .setTo("15165611976")
	            .setSignature("手机虾")
	            .setTemplateId("pub_verif_ttl3")
	            .setTemplateData(templateData);

	        // 发送短信
	        try {
	            UniResponse res = message.send();
	            System.out.println(res);
	        } catch (UniException e) {
	            System.out.println("Error: " + e);
	            System.out.println("RequestId: " + e.requestId);
	        }
	    }
}
